using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.UI;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SOEI.Solution.DomainEntities.CustomerManagement.DomainService;
using SOEI.Solution.DomainEntities.CustomerManagement.Dtos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace SOEI.Solution.DomainEntities.CustomerManagement
{
    /// <summary>
    /// 【扩展模块】  <br/>
    /// 【功能描述】  ：XXX 模块<br/>
    /// 【创建日期】  ：2020.05.21 <br/>
    /// 【开发人员】  ：static残影<br/>
    ///</summary>
    [ApiExplorerSettings(GroupName = "Manager", IgnoreApi = false)]
    public class SellerAppService : SolutionAppServiceBase, ISellerAppService
    {
        /// <summary>
        ///【Seller】仓储层
        /// </summary>
        private readonly IRepository<Seller, long> _sellerRepository;

        /// <summary>
        ///【Seller】领域服务
        /// </summary>
        private readonly ISellerManager _sellerManager;

        public SellerAppService(
            IRepository<Seller, long> sellerRepository,
            ISellerManager sellerManager
        )
        {
            _sellerRepository = sellerRepository;
            _sellerManager = sellerManager;
        }

        #region -------------------------------------------------辅助工具生成---------------------------------------------- 

        /// <summary>
        ///【客源管理-卖方】获取的分页列表信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task<PagedResultDto<SellerListDto>> GetPaged(GetSellersInput input)
        {
            //1. 获取当前登录的用户信息（）
            //2. 判断当前登录 是否经济机构用户
            await GetPersonChecker();

            var query = _sellerRepository.GetAll()
                          //模糊搜索 字段Name
                          .WhereIf(!input.Name.IsNullOrWhiteSpace(), a => a.Name.Contains(input.Name))
                          ////精确搜索 字段IdNumber
                          .WhereIf(!input.IdNumber.IsNullOrWhiteSpace(), a => a.IdNumber.Equals(input.IdNumber))
                          ////精确搜索 字段PreLocation
                          .WhereIf(!input.PhoneNumber.IsNullOrWhiteSpace(), a => a.PhoneNumber.Equals(input.PhoneNumber))
                          //精确搜索  字段UserTag
                          .WhereIf(!input.UserTag.IsNullOrWhiteSpace(), a => a.UserTag.Equals(input.UserTag))
            ;
            // TODO:根据传入的参数添加过滤条件

            var count = await query.CountAsync();

            var entityList = await query
                    .OrderBy(input.Sorting).AsNoTracking()
                    .PageBy(input)
                    .ToListAsync();

            var entityListDtos = ObjectMapper.Map<List<SellerListDto>>(entityList);

            return new PagedResultDto<SellerListDto>(count, entityListDtos);
        }

        /// <summary>
        ///【客源管理-卖方】通过指定id获取MemberListDto信息
        /// </summary>
        [AbpAuthorize()]
        public async Task<SellerListDto> GetById(EntityDto<long> input)
        {
            //Thread.Sleep(2000);
            var entity = await _sellerRepository.GetAsync(input.Id);

            var dto = ObjectMapper.Map<SellerListDto>(entity);
            return dto;
        }

        /// <summary>
        ///【客源管理-卖方】 获取编辑
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task<GetSellerForEditOutput> GetForEdit(NullableIdDto<long> input)
        {
            var output = new GetSellerForEditOutput();
            SellerEditDto editDto;

            if (input.Id.HasValue)
            {
                var entity = await _sellerRepository.GetAsync(input.Id.Value);
                editDto = ObjectMapper.Map<SellerEditDto>(entity);
            }
            else
            {
                editDto = new SellerEditDto();
            }
            output.Seller = editDto;
            return output;
        }
        /// <summary>
        ///【客源管理-卖方】 添加或者修改的公共方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task CreateOrUpdate(CreateOrUpdateSellerInput input)
        {
            //1. 获取当前登录的用户信息（）
            //2. 判断当前登录 是否经济机构用户
            await GetPersonChecker();

            if (input.Seller.Id.HasValue)
            {
                await Update(input.Seller);
            }
            else
            {
                await Create(input.Seller);
            }
        }
        /// <summary>
        ///【客源管理-卖方】新增
        /// </summary>
        [AbpAuthorize()]
        protected virtual async Task<SellerEditDto> Create(SellerEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增
            var Result = await _sellerManager.IsExistAsync(input.IdNumber);
            if (Result == true)
            {
                //抛异常
            }
            var entity = ObjectMapper.Map<Seller>(input);
            //调用领域服务
            entity = await _sellerManager.CreateAsync(entity);

            var dto = ObjectMapper.Map<SellerEditDto>(entity);
            return dto;
        }

        /// <summary>
        ///【客源管理-卖方】编辑
        /// </summary>
        [AbpAuthorize()]
        protected virtual async Task Update(SellerEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新
            var key = input.Id.Value;
            var entity = await _sellerRepository.GetAsync(key);
            //  input.MapTo(entity);
            //将input属性的值赋值到entity中
            ObjectMapper.Map(input, entity);
            await _sellerManager.UpdateAsync(entity);
        }

        /// <summary>
        ///【客源管理-卖方】删除信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task Delete(EntityDto<long> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            if (input != null)
            {
                var result = await _sellerManager.IsExistAsync(input.Id);
                if (result == true)
                {
                    await _sellerManager.DeleteAsync(input.Id);
                }
                else
                {
                    throw new Exception("该用户不存在!");
                }
            }
        }

        /// <summary>
        ///【客源管理-卖方】 批量删除Member的方法
        /// </summary>
        [AbpAuthorize()]
        public async Task BatchDelete(List<long> input)
        {
            // TODO:批量删除前的逻辑判断，是否允许删除
            if (input.Count > 0 && input != null)
            {
                await _sellerManager.BatchDelete(input);
            }
        }

        #endregion

        #region -------------------------------------------------用户自定义------------------------------------------------
        /*请在此扩展应用服务实现*/
        #endregion
    }
}
